package controllers

import (
	"errors"
	"github.com/astaxie/beego/logs"
	"strings"
	"wjp/models"
	"wjp/syserror"
)

type UserController struct {
	BaseController
}

// @router /login [post]
func (this *UserController) Login(){
	//username
	email := this.getMustString("email","用户名不能为空！")
	////password
	password := this.getMustString("password","密码不能为空！")
	//

	user,err:=models.QueryUserByUsernamePwd(email,password)
	logs.Info(err)
	if err!=nil{
		this.Abort500(syserror.New("登录失败",err))
		//logs.Info(err)
	}
	this.SetSession(SESSION_USER_KEY,user)
	this.JsonOk("登录成功","/")
}
// @router /reg [post]
func (this *UserController) Reg(){
	//username	////password
	name := this.getMustString("name","用户名不能为空！")
	email := this.getMustString("email","邮箱不能为空！")
	password := this.getMustString("password","密码不能为空！")
	password1 := this.getMustString("password1","确认密码不能为空！")

	if strings.Compare(password,password1)!=0{
		this.Abort500(errors.New("两次密码不一致"))
	}
	if user,err:=models.QueryUserByName(name);err==nil&&user.ID>0{
		this.Abort500(errors.New("用户昵称已存在"))
	}
	if user,err:=models.QueryUserByEmail(email);err==nil&&user.ID>0{
		this.Abort500(errors.New("用户邮箱已存在"))
	}

	if err :=models.SaveUser(&models.User{
		Name:name,
		Email:email,
		Pwd:password,
		Avartar:"/static/images/info-img.png",
		Role:1,
	});err!=nil{
		this.Abort500(errors.New("用户保存失败"))
	}

	this.JsonOk("注册成功","/user")
}

// @router /logout [get]
func (this *UserController) Logout(){
    this.MustLogin()
	this.DelSession(SESSION_USER_KEY)
	this.Redirect("/",302)
}